package renguanyu.app.auth4fx.controller.user;

import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.scene.control.CheckBox;
import renguanyu.app.auth4fx.service.user.UserRoleService;
import renguanyu.app.auth4fx.view.user.UserListView;
import renguanyu.app.auth4fx.view.user.UserRoleListView;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class UserRoleListSaveController extends Task<Void> {

    private UserRoleListView userRoleListView;
    public UserRoleListSaveController(UserRoleListView userRoleListView) {
        this.userRoleListView = userRoleListView;
    }

    public void execute() {
        System.out.println("UserRoleListSaveController.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private int rows = 0;
    int[] results;
    List<CheckBox> leftSelectedCheckBoxes;
    List<String> roleIds = new ArrayList<>();
    @Override
    protected Void call() {
        System.out.println("UserRoleListSaveController.call");
        String userId = UserListView.selectedUser.getId();
        leftSelectedCheckBoxes = userRoleListView.leftCheckBoxContainer.getChildren().stream().map(
            node -> {
                CheckBox checkBox = (CheckBox) node;
                return checkBox;
            }
        ).filter(CheckBox::isSelected).collect(Collectors.toList());
        int size = leftSelectedCheckBoxes.size();

        roleIds = userRoleListView.leftCheckBoxContainer.getChildren().stream().map(
            node -> {
                CheckBox checkBox = (CheckBox) node;
                return checkBox;
            }
        ).filter(CheckBox::isSelected).map(e->{
            ObservableMap<Object, Object> properties = e.getProperties();
            String id = properties.get("id").toString();
            return id;
        }).collect(Collectors.toList());

        results = UserRoleService.saveUserRoleList(size, userId, roleIds);
        return null;
    }

    @Override
    protected void running() {
        System.out.println("UserRoleListSaveController.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("UserRoleListSaveController.succeeded");
        if(results.length >= 1){
            userRoleListView.leftCheckBoxContainer.getChildren().removeAll(leftSelectedCheckBoxes);
            leftSelectedCheckBoxes.forEach(checkBox -> {
                userRoleListView.rightCheckBoxContainer.getChildren().add(checkBox);
            });
        }
    }

    @Override
    protected void failed() {
        System.out.println("UserRoleInfoSave.failed");
    }
}
